/**
 * @author yanggjun
 */

ObstacleCheck = {
		offset : 100,
		collide: function (enemyIndex, type){
//			type = 0 check whether there is wall between enemy and player
//			type = 1 check whether target the wall when player fires.
			var m,n,p;
			if(type == 0){
				m = EnemyModel[enemyIndex].pos.x - PlayMan.pos.x;
				n = EnemyModel[enemyIndex].pos.y - PlayMan.pos.y;
				p = EnemyModel[enemyIndex].pos.z - PlayMan.pos.z;
			}else if(type == 1){
//				m = CameraController.lookAtPos.x - PlayMan.pos.x;
//				n = CameraController.lookAtPos.y - PlayMan.pos.y;
//				p = CameraController.lookAtPos.z - PlayMan.pos.z;
				m = TargetIndicator.pos.x - PlayMan.pos.x;
				n = TargetIndicator.pos.y - PlayMan.pos.y;
				p = TargetIndicator.pos.z - PlayMan.pos.z;
			}
			
			var x1,y1,z1;
			if(type == 0){
				x1 = EnemyModel[enemyIndex].pos.x;
				y1 = EnemyModel[enemyIndex].pos.y;
				z1 = EnemyModel[enemyIndex].pos.z;
			}else if(type == 1){
//				x1 = CameraController.lookAtPos.x;
//				y1 = CameraController.lookAtPos.y;
//				z1 = CameraController.lookAtPos.z;
				x1 = TargetIndicator.pos.x;
				y1 = TargetIndicator.pos.y;
				z1 = TargetIndicator.pos.z;
				
			}
			
			for(var i=0; i<World.modelList.length; i++){
				var obstacle = World.modelList[i];
				var wallList = obstacle.wallList;
//				back
				var k = 0;
				for(var j=0; j<wallList.length; j++){
					var wall = wallList[j];
					var M = wall.vector.x;
					var N = wall.vector.y;
					var P = wall.vector.z;
					if(M*m + N*n + P*p == 0)
						continue;					
					
					var x0 = (wall.lt.x + wall.rt.x)/2;
					var y0 = (wall.lt.y + wall.rt.y)/2;
					var z0 = (wall.lt.z + wall.rt.z)/2;
					
					
					k -= (M*(x1-x0) + N*(y1-y0) + P*(z1-z0))/(M*m + N*n + P*p);
					//console.log("k= "+ k);
					var px = k*m + x1;
					var py = k*n + y1;
					var pz = k*p + z1;
					if(M == 1 || M == -1){
//						console.log("pz:" + pz + "wall.lt.z:"+ wall.lt.z + " wall.rt.z:" + wall.rt.z);
						if(pz > wall.lt.z + this.offset  && pz < wall.rt.z - this.offset &&
								py > 0 && py < wall.rt.y){
//							console.log(" you shoot the wall " + i);
//							
							return true;
						}
					}else if( P == 1 || P == -1){
//						console.log("px" + px + "wall.lt.x:"+ wall.lt.x + " wall.rt.x:" + wall.rt.x);
						if(px > wall.lt.x + this.offset && px < wall.rt.x - this.offset &&
								py > 0 && py < wall.rt.y){
//							console.log(" you shoot the wall ~~~~~~~" + i);
							return true;
						}
					}
				}
			}
			
		}
}